package com.example.springbootshiro.util;

import com.alibaba.fastjson.JSON;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.lang3.ObjectUtils;

import java.util.Date;
import java.util.HashMap;

public class JwtUtil {
    //request中保存token的字段
    private static String key = "Authentication";
    //claimName
    private static String claimName = "TOKEN_OBJECT_8HJD7YS";
    //秘钥
    private static String secret = "sif3%uf_ie12$%^$";
    //有效时间（秒）
    private static long expire = 60 * 60 * 24 * 3;


    /**
     * 创建token
     *
     * @param obj
     * @return
     */
    public static String createToken(Object obj) {
        HashMap<String, Object> bodyMap = new HashMap<>();
        bodyMap.put(claimName, JSON.toJSONString(obj));
        return Jwts.builder()
                .setClaims(bodyMap)
                .setExpiration(new Date(System.currentTimeMillis() + expire * 1000L))
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }

    /**
     * 解析token
     *
     * @param token
     * @param clazz
     * @param <T>
     * @return
     * @throws ExpiredJwtException token已过期异常
     */
    public static <T> T parsing(String token, Class<T> clazz) throws ExpiredJwtException {
        if (ObjectUtils.isEmpty(token)) return null;
        Claims claims = Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token)
                .getBody();
        String userJson = claims.get(claimName, String.class);
        return JSON.parseObject(userJson, clazz);
    }


}
